# -*- coding: utf-8 -*-
"""事件处理器模块"""


class EventHandlers:
    """管理应用程序中的各类事件处理"""

    def __init__(self, main_window):
        """初始化事件处理器

        Args:
            main_window: 主窗口实例
        """
        self.main_window = main_window

    def handle_file_open(self):
        """处理文件打开事件"""
        try:
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            file_path = dialog_manager.show_file_dialog(
                title="打开Excel文件",
                file_types=[("Excel Files", "*.xlsx *.xls")],
            )

            if file_path:
                self.main_window.status_var.set(f"正在导入文件: {file_path}")
                self.main_window.root.update_idletasks()

                # 导入数据
                self.main_window.original_data = (
                    self.main_window.data_importer.import_excel_file(file_path)
                )

                # 显示数据
                self.main_window._display_data(self.main_window.original_data)

                self.main_window.status_var.set(f"成功导入文件: {file_path}")
                dialog_manager.show_message_dialog(
                    title="成功", message=f"文件导入成功: {file_path}"
                )
        except Exception as e:
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="错误",
                message=f"文件导入失败: {str(e)}",
                message_type="error",
            )
            self.main_window.status_var.set("文件导入失败")

    def handle_process_data(self):
        """处理数据处理事件"""
        if (
            self.main_window.original_data is None
            or self.main_window.original_data.empty
        ):
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="警告", message="请先导入数据", message_type="warning"
            )
            return

        try:
            self.main_window.status_var.set("正在处理数据...")
            self.main_window.root.update_idletasks()

            # 预处理数据
            self.main_window.processed_data = (
                self.main_window.data_preprocessor.clean_data(
                    self.main_window.original_data
                )
            )
            self.main_window.processed_data = (
                self.main_window.data_preprocessor.standardize_data(
                    self.main_window.processed_data
                )
            )

            # 显示处理后的数据
            self.main_window._display_data(self.main_window.processed_data)

            self.main_window.status_var.set("数据处理完成")

            # 显示分析结果
            analysis_result = self.main_window.data_preprocessor.analyze_data(
                self.main_window.processed_data
            )
            analysis_text = (
                f"数据分析结果:\n"
                f"总记录数: {analysis_result['total_records']}\n"
                f"唯一客户数: {analysis_result['unique_customers']}\n"
                f"唯一规格型号数: {analysis_result['unique_specifications']}\n"
                f"总数量: {analysis_result['total_quantity']}"
            )

            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="数据处理完成", message=analysis_text
            )
        except Exception as e:
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="错误",
                message=f"数据处理失败: {str(e)}",
                message_type="error",
            )
            self.main_window.status_var.set("数据处理失败")

    def handle_match_packaging(self):
        """处理包装方案匹配事件"""
        if (
            self.main_window.processed_data is None
            or self.main_window.processed_data.empty
        ):
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="警告", message="请先处理数据", message_type="warning"
            )
            return

        try:
            self.main_window.status_var.set("正在匹配包装方案...")
            self.main_window.root.update_idletasks()

            # 这里假设历史数据已经加载
            # 实际应用中应该从文件或数据库加载历史数据
            historical_data = None  # 需要替换为实际的历史数据加载逻辑

            # 执行匹配
            self.main_window.matched_data = (
                self.main_window.data_matcher.match_specification(
                    self.main_window.processed_data, historical_data
                )
            )

            # 识别包装类型
            self.main_window.matched_data = (
                self.main_window.data_matcher.identify_package_type(
                    self.main_window.matched_data
                )
            )

            # 分类数据
            self.main_window.matched_data = (
                self.main_window.data_matcher.classify_data(
                    self.main_window.matched_data
                )
            )

            # 显示匹配结果
            self.main_window._display_data(self.main_window.matched_data)

            self.main_window.status_var.set("包装方案匹配完成")
        except Exception as e:
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="错误",
                message=f"包装方案匹配失败: {str(e)}",
                message_type="error",
            )
            self.main_window.status_var.set("包装方案匹配失败")

    def handle_generate_results(self):
        """处理生成结果事件"""
        if (
            self.main_window.matched_data is None
            or self.main_window.matched_data.empty
        ):
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="警告",
                message="请先匹配包装方案",
                message_type="warning",
            )
            return

        try:
            self.main_window.status_var.set("正在生成结果...")
            self.main_window.root.update_idletasks()

            # 处理结果
            self.main_window.results = (
                self.main_window.result_processor.process_results(
                    self.main_window.matched_data
                )
            )

            # 优化结果
            self.main_window.results = (
                self.main_window.result_processor.optimize_results(
                    self.main_window.results
                )
            )

            # 显示结果
            self.main_window._display_data(self.main_window.results)

            self.main_window.status_var.set("结果生成完成")
        except Exception as e:
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="错误",
                message=f"结果生成失败: {str(e)}",
                message_type="error",
            )
            self.main_window.status_var.set("结果生成失败")

    def handle_export_results(self):
        """处理导出结果事件"""
        if self.main_window.results is None or self.main_window.results.empty:
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="警告", message="请先生成结果", message_type="warning"
            )
            return

        try:
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            file_path = dialog_manager.show_save_dialog(
                title="导出结果",
                file_types=[("Excel Files", "*.xlsx")],
                default_filename="包装方案匹配结果.xlsx",
            )

            if file_path:
                self.main_window.status_var.set(f"正在导出结果到: {file_path}")
                self.main_window.root.update_idletasks()

                # 导出结果
                self.main_window.result_processor.export_results(
                    self.main_window.results, file_path
                )

                self.main_window.status_var.set(f"结果导出完成: {file_path}")
                dialog_manager.show_message_dialog(
                    title="成功", message=f"结果导出成功: {file_path}"
                )
        except Exception as e:
            from .dialogs import DialogManager

            dialog_manager = DialogManager()
            dialog_manager.show_message_dialog(
                title="错误",
                message=f"结果导出失败: {str(e)}",
                message_type="error",
            )
            self.main_window.status_var.set("结果导出失败")
